<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="card-header">
        <span class="title">修改验收标准</span>
        <div class="btn-wrap">
          <el-button
            v-if="showBtn('高级关联')"
            size="middle"
            type="text"
            @click="handleSeniorLinked"
            >高级关联</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <el-button
            v-if="showBtn('关联商品')"
            size="middle"
            type="text"
            @click="handleAssociateProduct"
            >关联商品</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <el-button
            size="middle"
            type="text"
            :loading="exportLoading"
            @click="handleExportFile"
            >模板导出</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <el-upload
            class="import-file"
            ref="bacthUpload"
            :action="`${uploadBaseURL}sysback/product/batchUpdatePotentialStandard/importExcel`"
            accept=".xls, .xlsx"
            :before-upload="beforeFileUpload"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :show-file-list="false"
          >
            <el-button size="middle" type="text" :loading="importBtnLoading"
              >模板导入</el-button
            >
          </el-upload>
          <el-divider direction="vertical"></el-divider>
          <el-button
            size="middle"
            type="text"
            :loading="saveBtnLoading"
            @click="handleSubmit"
            >提交</el-button
          >
        </div>
      </div>
      <div>
        <Umy-table
          :loading="tableLoading"
          :data-source="baseTableData"
          :columns="tableColumns"
          :isShowSortNum="true"
          :tableHeight="500"
          @handleCancelSelect="handleCancelSelect"
        />
      </div>
    </el-card>
    <RelatedGoods
      ref="associateDialog"
      :pageType="'edit'"
      :dialogVisible="dialogVisible"
      @query-data="handleQueryTableData"
      @hide-handler="handleCloseDialog"
    />
    <!-- 高级关联弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="getSeniorResultFn"
    />
  </div>
</template>
<script>
import UmyTable from '@/components/UmyTable';
import RelatedGoods from './components/RelatedGoods';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import { isResponseSuccess, setAuthBtnId, createExcelByExport } from '@/utils/bizUtils';
import { mapGetters } from 'vuex';
import {
  queryStandardListForEditService,
  submitStandardForEditService,
  exportStandardEditService
} from '@api/commodity/temporaryPurchasingGoods/acceptanceStandard'
import {
  BATCH_EDIT_TABLE_COLUMNS,
  BATCH_EDIT_TABLE_CHILDREN_COLUMNS1,
  BATCH_EDIT_TABLE_CHILDREN_COLUMNS2,
} from './constants'

export default {
  mixins: [],
  components: {
    UmyTable,
    RelatedGoods,
    SeniorLinkedDialog
  },
  data () {
    return {
      skuNos: [],
      dialogVisible: false,
      exportLoading: false,
      importBtnLoading: false,
      tableLoading: false,
      saveBtnLoading: false,
      baseTableData: [], // 列表的数据源
      tableColumns: [],
      seniorLinked: {
        visible: false,
        columns: [{
          label: 'SKU编码',
          prop: 'skuNo',
          type: 'textarea'
        }],
        dataSource: [{ skuNo: '' }],
        isSenior: false
      }
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  created () {
    this.initTabaleClonum();
  },
  methods: {
    initTabaleClonum () {
      this.tableColumns = _.cloneDeep(BATCH_EDIT_TABLE_COLUMNS);
    },
    async handleQueryTableData (skuList) {
      let skuNoList = this.skuNos.concat(skuList);
      this.baseTableData = [];
      const isNullSkuNos = (skuNoList ?? []).filter(item => item).length == 0
      if (isNullSkuNos) return
      this.tableColumns = [];
      const res = await queryStandardListForEditService(
        { skuNos: [...new Set(skuNoList)] },
        state => { this.tableLoading = state }
      )
      if (res) {
        const { retData } = res;
        this.handleFormatTableData(retData);
        this.skuNos = [...new Set(skuNoList)];
      } else {
        this.initTabaleClonum();
      }
    },
    handleFormatTableData (reData) {
      this.baseTableData = [];
      this.tableColumns = [];
      this.initTabaleClonum();
      reData.forEach((element, oneIndex) => {
        // 准备一行数据的普通列
        let curRow = {
          productName: element.productName,
          brandName: element.brandName,
          categoryPath: element.categoryPath,
          categoryUuid: element.categoryUuid,
          spuNo: element.spuNo,
          skuNo: element.skuNo,
          checkTime: element.checkTime,
          checkTimeUpdate: element.checkTimeUpdate,
          specDetail: element.specDetail,
          checkFrequency: element.checkFrequency,
          checkFrequencyUpdate: element.checkFrequencyUpdate,
          detailList: element.detailList
        };
        // 新建表头。并准备一行数据的动态列
        element.detailList.forEach((item, index) => {
          this.pushItem(oneIndex, curRow, item, index);
        });
        // 将行，添加到展示列表
        this.baseTableData.push(curRow);
      });
      this.tableColumns.push({
        title: '操作',
        key: 'action',
        align: 'center',
        fixed: 'right',
        width: 90
      });
    },
    pushItem (oneIndex, curRow, innerEle, index) {
      curRow['checkCount' + index] = innerEle.checkCount;
      curRow['checkCountUpdate' + index] = innerEle.checkCountUpdate;
      // 标准值
      curRow['standardValue' + index] = innerEle.standardValue;
      curRow['standardValueUpdate' + index] = innerEle.standardValueUpdate;
      // 上差值
      curRow['upDiffValue' + index] = innerEle.upDiffValue;
      curRow['upDiffValueUpdate' + index] = innerEle.upDiffValueUpdate;
      // 下差值
      curRow['downDiffValue' + index] = innerEle.downDiffValue;
      curRow['downDiffValueUpdate' + index] = innerEle.downDiffValueUpdate;
      // 验收方法
      curRow['checkMethod' + index] = innerEle.checkMethod;
      curRow['checkMethodUpdate' + index] = innerEle.checkMethodUpdate;
      // 1数字5个列可填，2文本3个列可填
      curRow['checkItemType' + index] = innerEle.checkItemType;
      // 表头，遍历第1行的动态列时，才追加到表头
      if (oneIndex === 0) {
        const children1 = _.cloneDeep(BATCH_EDIT_TABLE_CHILDREN_COLUMNS1)
        const children2 = _.cloneDeep(BATCH_EDIT_TABLE_CHILDREN_COLUMNS2)
        children1.forEach(i => {
          i.key = `${i.key}${index}`
        })
        children2.forEach(i => {
          i.key = `${i.key}${index}`
        })
        this.tableColumns.push({
          title: innerEle.checkItemName,
          required: innerEle.isNeed === '1',
          key: innerEle.checkItemUuid,
          width: 150,
          align: 'center',
          children: innerEle.checkItemType !== '2' ? children1 : children2
        });
      }
    },
    // 格式化提交数据
    formatSubmitData () {
      let submitList = [];
      this.baseTableData.forEach((element) => {
        element.detailList.forEach((item, innerI) => {
          item.checkCountUpdate = element['checkCountUpdate' + innerI];
          item.standardValueUpdate = element['standardValueUpdate' + innerI];
          item.upDiffValueUpdate = element['upDiffValueUpdate' + innerI];
          item.downDiffValueUpdate = element['downDiffValueUpdate' + innerI];
          item.checkMethodUpdate = element['checkMethodUpdate' + innerI];
        });
        submitList.push({
          brandName: element.brandName,
          categoryPath: element.categoryPath,
          categoryUuid: element.categoryUuid,
          productName: element.productName,
          specDetail: element.specDetail,
          skuNo: element.skuNo,
          spuNo: element.spuNo,
          checkFrequencyUpdate: element.checkFrequencyUpdate,
          checkTimeUpdate: element.checkTimeUpdate,
          detailList: element.detailList
        });
      });
      return submitList;
    },
    // 提交
    async handleSubmit () {
      if (this.baseTableData.length == 0) {
        return this.$message.warning('请关联商品后提交')
      }
      const res = await submitStandardForEditService(
        { commitList: this.formatSubmitData() },
        state => { this.saveBtnLoading = state }
      )
      if (res) {
        this.$Message.success('提交成功');
        this.$router.go(-1);
      }
    },
    beforeFileUpload () {
      this.baseTableData = [];
      this.tableLoading = true;
      this.importBtnLoading = true;
    },
    uploadSuccess (res) {
      this.tableLoading = false;
      this.importBtnLoading = false;
      if (isResponseSuccess(res)) {
        this.skuNos = res.retData.map((item) => {
          return item.skuNo;
        });
        let reData = res.retData;
        this.handleFormatTableData(reData);
      } else {
        this.$message.error(res.retMessage || '模板导入异常');
      }
    },
    uploadError (file) {
      this.tableLoading = false;
      this.importBtnLoading = false;
      this.$message.error('模板导入异常');
    },
    handleAssociateProduct () {
      console.log('关联商品');
      this.$refs.associateDialog.handleEmptySkus();
      this.dialogVisible = true;
    },
    handleCloseDialog (skuList) {
      this.dialogVisible = false;
      this.getGoodsResultFn(skuList);
    },
    // 删除
    handleCancelSelect (obj) {
      const { index, row } = obj;
      this.baseTableData.splice(index, 1);
      this.skuNos = this.skuNos.filter((item) => {
        console.log(item);
        return item != row.skuNo;
      });
    },
    // 导出
    async handleExportFile () {
      if (this.baseTableData.length === 0) {
        return this.$message.warning('请先关联商品');
      }
      const res = await exportStandardEditService(
        { exportList: this.formatSubmitData() },
        state => { this.exportLoading = state }
      )
      if (res) {
        createExcelByExport({ excelTitle: '修改验收标准模板', res })
      }
    },
    // 高级关联
    handleSeniorLinked () {
      setAuthBtnId('高级关联');
      this.seniorLinked.visible = true;
    },
    // 获取高级关联结果
    getSeniorResultFn (skuNos) {
      if (!this.seniorLinked.isSenior) {
        this.skuNos = [];
      }
      this.seniorLinked.isSenior = true;
      this.handleQueryTableData(skuNos);
    },
    // 获取关联商品结果
    getGoodsResultFn (skuNoList) {
      if (this.seniorLinked.isSenior) {
        this.skuNos = [];
      }
      this.seniorLinked.isSenior = false;
      this.handleQueryTableData(skuNoList);
    }
  }
};
</script>
<style lang="less" scoped>
.btn-wrap {
  float: right;
  .import-file {
    display: inline;
  }
}
.card-header {
  .title {
    font-size: 16px;
  }
}
</style>
